package com.dyzx.hbb.modules.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseCustomController;
import com.dyzx.hbb.modules.sys.entity.SysRole;
import com.dyzx.hbb.modules.sys.service.SysRoleMenuService;
import com.dyzx.hbb.modules.sys.service.SysRoleService;
import com.dyzx.hbb.modules.sys.service.SysRoleUserService;
import com.dyzx.hbb.modules.sys.vo.RoleUVO;
import com.dyzx.hbb.modules.sys.vo.RoleVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 角色管理控制器
 * 负责处理角色的增删改查、菜单权限分配等操作
 */
@RequestMapping("/sys/role")
@RestController
@Tag(name = "06.角色管理", description = "角色相关接口，包括角色的增删改查、菜单权限分配等")
public class RoleController extends BaseCustomController<SysRoleService, SysRole, RoleVO> {

    @Autowired
    private SysRoleService service;
    @Autowired
    private SysRoleMenuService roleMenuService;

    @Autowired
    private SysRoleUserService userRoleService;


    @Override
    protected SysRoleService getBaseService() {
        return service;
    }


    @Override
    protected MyLambdaQueryWrapper<SysRole> queryWrapper(RoleVO query) {
        MyLambdaQueryWrapper<SysRole> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.select(SysRole::getId, SysRole::getName, SysRole::getOrganId, SysRole::getRemark,SysRole::getCreateDate, SysRole::getUpdateDate,SysRole::getStatus).organName(SysRole::getOrganId).as("organ_name");

        if (query != null) {
            Long organId = SecurityContextHolder.getOrganId();

            wrapper.like(StringUtils.isNotBlank(query.getName()), SysRole::getName, query.getName()).eq(SecurityContextHolder.isNotAdmin(), SysRole::getOrganId, organId);
            return wrapper;
        } else {
            return wrapper;
        }

    }
    /**
     * 获取角色简易列表
     * @return 角色简易列表
     */
    @Operation(summary = "获取角色简易列表", description = "获取系统角色的简易列表，包含基本信息")
    @GetMapping("/mini_list")
    public Result<List<Map<String, Object>>> miniList() {

        List<Map<String, Object>> list=service.findByMiniList();
        return Result.ok(list);
    }

    /**
     * 新增角色
     * @param entity 角色信息对象
     * @return 操作结果
     */
    @Operation(summary = "新增角色", description = "添加新的系统角色，并分配菜单权限")
    @PostMapping
    public Result<Boolean> add(
            @Parameter(description = "角色信息对象") @RequestBody RoleVO entity) {
        System.out.println("角色名称：" + entity.getName());
        if (entity == null) {
            return Result.error("参数不能为空");
        }
        Long organId = SecurityContextHolder.getOrganId();
        Long opratorId = SecurityContextHolder.getUserId();
        SysRole entityCopy = new SysRole();
        BeanUtil.copyProperties(entity,entityCopy);
        System.out.println(entityCopy);
        entityCopy.setOperatorId(opratorId);
        System.out.println("角色名称：" + entityCopy.getName());
        entityCopy.setOrganId(organId);
        boolean save = getBaseService().save(entityCopy);
        if (save && entity.getMenuIds() != null) {
            System.out.println("菜单id：" + entity.getMenuIds());
            String[] split = entity.getMenuIds().split(",");
            List<Long> mids= Arrays.stream(split).map(Long::parseLong).toList();
            roleMenuService.assignMenus(entityCopy.getId(), mids);
        }
        return save ? Result.ok() : Result.error("保存失败");
    }
    /**
     * 删除角色
     * @param id 角色ID
     * @return 操作结果
     */
    @Operation(summary = "删除角色", description = "根据ID删除系统角色")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(
            @Parameter(description = "角色ID") @PathVariable Long id) {
        if (id == null) {
            return Result.error("id不能为空");
        }
        boolean result = getBaseService().removeById(id);
        return result ? Result.ok() : Result.error("删除失败");
    }

    //修改角色
    @Operation(summary = "修改")
    @PutMapping
    public Result<Boolean> update(@RequestBody RoleUVO entity) {
        if (entity == null) {
            return Result.error("参数不能为空");
        }
        SysRole entityCopy = new SysRole();
        BeanUtil.copyProperties(entity, entityCopy);
     //   entityCopy.setOrganId(organId);
        boolean update = getBaseService().updateById(entityCopy);
        if (update && entity.getMenuIds() != null) {
            String[] split = entity.getMenuIds().split(",");
            List<Long> mids= Arrays.stream(split).map(Long::parseLong).toList();
            roleMenuService.assignMenus(entityCopy.getId(),mids);
        }
        return update ? Result.ok(true) : Result.error("保存失败");
    }



    @Override
    protected MyLambdaQueryWrapper<SysRole> queryInfoWrapper() {

        MyLambdaQueryWrapper<SysRole> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.select(SysRole::getId, SysRole::getName, SysRole::getOrganId, SysRole::getRemark,SysRole::getCreateDate, SysRole::getUpdateDate,SysRole::getStatus);

        return wrapper;
    }

    @Operation(summary = "分配菜单")
    @PostMapping("/menu/{roleId}")
    public Result<Boolean> assignMenus(@PathVariable Long roleId, @RequestParam  String menuIds) {
        String[] split = menuIds.split(",");
        List<Long> mids= Arrays.stream(split).map(Long::parseLong).toList();
        boolean result = roleMenuService.assignMenus(roleId, mids);
        return Result.ok(result);
    }

    @Operation(summary = "获取角色菜单")
    @GetMapping("/menu/{roleId}")
    public Result<List<Long>> getMenus(@PathVariable Long roleId) {
        List<Long> menuIds = roleMenuService.getMenuIdsByRoleId(roleId);
        return Result.ok(menuIds);
    }

    @Operation(summary = "删除角色菜单分配")
    @DeleteMapping("/menu/{roleId}")
    public Result<Boolean> deleteRoleMenus(@PathVariable Long roleId,  String menuIds) {
        String[] split = menuIds.split(",");
        List<Long> mids= Arrays.stream(split).map(Long::parseLong).toList();
        boolean result = roleMenuService.deleteRoleMenus(roleId, mids);
        return Result.ok(result);
    }

    @Operation(summary = "分配用户")
    @PostMapping("/user/{roleId}")
    public Result<Boolean> assignUsers(@PathVariable Long roleId,  String userIds) {
        String[] split = userIds.split(",");
        List<Long> mids= Arrays.stream(split).map(Long::parseLong).toList();
        boolean result = userRoleService.assignUsers(roleId, mids);
        return Result.ok(result);
    }

    @Operation(summary = "获取角色用户")
    @GetMapping("/user/{roleId}")
    public Result<List<Long>> getUsers(@PathVariable Long roleId) {
        List<Long> userIds = userRoleService.getUserIdsByRoleId(roleId);
        return Result.ok(userIds);
    }

    @Operation(summary = "删除角色用户分配")
    @DeleteMapping("/user/{roleId}")
    public Result<Boolean> deleteRoleUsers(@PathVariable Long roleId, String userIds) {
        String[] split = userIds.split(",");
        List<Long> mids= Arrays.stream(split).map(Long::parseLong).toList();
        boolean result = userRoleService.deleteRoleUsers(roleId, mids);
        return Result.ok(result);
    }

}
